const Router = require('koa-router')
const { find, findById, create, update, del, login, gitlogin } = require(':controllers/user')
const JWT = require(':JWT')
const router = new Router({ prefix: '/user' }) // 给路由加前缀
const auth = async(ctx, next) => {
  const { authorization = '' } = ctx.request.header
  const token = authorization.replace('Bearer', '')
  console.log(authorization)
  try {
    const user = JWT.verify(token.secret)
    ctx.state.user = user
  } catch (err) {
    ctx.throw(401)
  }
  await next()
}

const checkOwner = async(ctx, next) => {
  if (ctx.params.id !== ctx.state.user._id) {
    // 如果请求的id 与登录的不是同一个
    ctx.throw(403, '没权限')
  }
  await next()
}
const checkLogin = async()=> {
  console.log(92313123)
  // if(['/login'].indexOf(ctx.url)!==-1){
  // await next();
  // return;
  // }
  // const isLogin = await valid();
  // if(!isLogin) {
  //     ctx.throw(401);
  // }
  await next();
}
// router.use(checkLogin);
//github第三方登录p
router.get('/getgitinfo/:code', gitlogin)
// console.log('/:id')
router.get('/:id', findById)

// router.post('/', create)

// router.patch('/:id', auth, checkOwner, update) // patch 只修改部分

// router.delete('/:id', del)

// router.post('/', login)

module.exports = router

// function debounce(fn, time) {
//   let timer = null
//   return function(...args) {
//     timer = setTimeout(() => {
//       fn(...args)
//     }, time)
//   }
// }
